1325C - Ehab and Path-etic MEXs - CodeForces Solution


constructive algorithms dfs and similar greedy trees *1500

Please click on ads to support us..

Python Code:

n = int(input());jaya= [0]*(n+1);l = []
for i in range(n-1):
	a,b = map(int,input().split());a -= 1;b -= 1;jaya[a] += 1;jaya[b] += 1;l.append([a,b])
m = 0;mex = n-2
for a,b in l:
	if jaya[a] == 1 or jaya[b] == 1:print(m);m+= 1
	else:print(mex);mex -= 1

C++ Code:

#include <bits/stdc++.h>
using namespace std;
void solve_task(){
    int n;
    scanf("%d", &n);
    int cnt[n];
    memset(cnt,0,sizeof cnt);
    vector< pair<int, int> > ed[n];
    for(int i=1;i<n;i++){
        int a,b;
        scanf("%d%d",&a,&b);
        a--,b--;
        ed[a].push_back({b,i});
        ed[b].push_back({a,i});
    }
    int nxt=0,ans[n],vis[n];
    memset(ans,-1,sizeof ans);
    memset(vis,0,sizeof vis);
    queue<int> q;
    for(int i=0;i<n;i++){
        if(ed[i].size()>1)continue;
        q.push(i);
        vis[i]=1;
    }
    for(;!q.empty();q.pop()){
        auto i=q.front();
        for(auto [j,pos]:ed[i]){
            if(ans[pos]==-1)ans[pos]=nxt++;
            if(!vis[j]){
                q.push(j);
                vis[j]=1;
            }
        }
    }
    for(int i=1;i<n;i++){
        printf("%d\n",ans[i]);
    }
}
int main(){
    int t = 1;
    while(t--){
        solve_task();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings